package com.sf.fy.uav.common.config;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;

/**
 * @author 01430312
 */
@Configuration
public class RedissonConfig {

    Logger log = LoggerFactory.getLogger(RedissonConfig.class);


    /**
     * 直接使用starter注入的redis配置信息
     */
    @Autowired
    private RedisProperties redisProperties;

    private int timeout = 3000;
    private int connectionPoolSize = 64;
    private int connectionMinimumIdleSize = 10;
    private int pingConnectionInterval = 60000;
    private static String ADDRESS_PREFIX = "redis://";

    /**
     * 单机模式
     */
    @Bean
    public RedissonClient initBean() {
        // 哨兵模式
        RedisProperties.Sentinel sentinel = redisProperties.getSentinel();
        if (Objects.nonNull(sentinel)) {
            log.info("redis is sentinel mode");
            return redissonSentinel();
        }
        log.error("redisson config can not support this redis mode");
        return null;
    }


    /**
     * 哨兵模式
     */
    private RedissonClient redissonSentinel() {
        // my_master
        String masterName = redisProperties.getSentinel().getMaster();
        // 127.0.0.1:26389,127.0.0.1:26379
        List<String> nodes = redisProperties.getSentinel().getNodes();
        String password = redisProperties.getPassword();
        // 声明一个配置类
        Config config = new Config();
        SentinelServersConfig sentinelServersConfig = config.useSentinelServers();
        // 扫描间隔
        sentinelServersConfig.setScanInterval(2000);
        // 判断密码
        if (!StringUtils.isEmpty(password)) {
            sentinelServersConfig.setPassword(password);
        }
        sentinelServersConfig.setMasterName(masterName);
        String[] nodeArr = nodes.toArray(new String[]{});
        for (int i = 0; i < nodeArr.length; i++) {
            nodeArr[i] = ADDRESS_PREFIX + nodeArr[i];
        }
        // 添加redis节点
        sentinelServersConfig.addSentinelAddress(nodeArr);
        return Redisson.create(config);
    }
}